#pragma once

#include <iostream>
#include <string>
#include <unistd.h>
#include <functional>
#include "InterAddr.hpp"
#include "Reactor.hpp"

//对文件描述符进行封装
// 一份fd，在我们心里也是相当于一个Connection对象
// listensockfd 也是一样的看作Connection对象 
class Reactor;
class Connection;
using func_t = std::function<void(Connection*)>;

class Connection
{
public:
    Connection(int sock):_sock(sock)
    {}
    void SetEvents(uint32_t events)
    {
        _events = events;
    }
    uint32_t Events()
    {
        return _events;
    }
    int Sockfd()
    {
        return _sock;
    }
    void Register(func_t recver,func_t sender,func_t excpter)
    {
        _recver = recver;
        _sender = sender;
        _excpter = excpter;
    }

    void SetSelf(Reactor* R)
    {
        _R = R;
    }

    void AppendInBuffer(const std::string &buffer)
    {
        _inbuffer += buffer;
    }
    void AppendOutBuffer(const std::string &buffer)
    {
        _outbuffer += buffer;
    }
    std::string& Inbuffer() // 这里引用返回
    {
        return _inbuffer;
    }

    bool OutBufferEmpty()
    {
        return _outbuffer.empty();
    }

    std::string &OutBuffer()
    {
        return _outbuffer;
    }

    void OutBufferRemove(int n)
    {
        _outbuffer.erase(0, n);
    }

    void Close()
    {
        if (_sock >= 0)
        {
            ::close(_sock);
        }
    }
    ~Connection()
    {}
private:
    int _sock;
    std::string _inbuffer;
    std::string _outbuffer;

    InterAddr _addr;

    uint32_t _events; // connenction对象中_sock关系的事件集合

public:
    func_t _recver;
    func_t _sender;
    func_t _excpter;
    Reactor* _R;
};